import "../sass/pay.scss";

import { useLocation, useNavigate } from "react-router-dom";

import { useState, useEffect } from "react";

import {
    ProductCard,
    Button,
    Popup,
    Cell,
    Radio,
    NavBar,
} from "react-vant";

import axios from "axios";

import { useSelector, useDispatch } from "react-redux";

import { changeCount } from "../store/store";

function Pay() {
    let navigate = useNavigate();

    let location = useLocation();
    //

    let shopbagCount = useSelector(
        (state) => state.publicModule.count
    );

    let dispatch = useDispatch();

    let [visible, setVisible] = useState(false);

    //地址数据
    let [addressData, setAddressData] = useState([]);

    let [selectIndex, setSelectIndex] = useState(-1);

    //选择的地址数据
    let [selectAddressData, setSelectAddressData] =
        useState({
            phone: "",
            address: "",
            receiver: "",
        });

    //需要结算的购物袋商品数据
    let [payProduct, setPayProduct] = useState([]);

    //商品数量、订单总价
    let [payInfo, setPayInfo] = useState({
        count: 0,
        total: 0,
    });

    //获取地址数据
    let getAddressList = () => {
        axios({
            method: "get",
            url: "/findAddress",
        })
            .then((res) => {
                if (res.data.code === 700) {
                    return navigate("/login");
                }

                if (res.data.code === 20000) {
                    res.data.result.forEach(
                        (item, index) => {
                            item.address = `${item.province}${item.city}${item.county}${item.addressDetail}`;

                            //默认勾选默认地址
                            if (Boolean(item.isDefault)) {
                                setSelectIndex(index);

                                //修改选择地址数据
                                setSelectAddressData({
                                    phone: item.tel,
                                    address: item.address,
                                    receiver: item.name,
                                });
                            }
                        }
                    );

                    setAddressData(res.data.result);
                }
            })
            .catch((err) => {});
    };

    //选择地址
    let selectAddress = (index) => {
        setSelectIndex(index);

        let currentAddressData = addressData[index];

        //修改选择地址数据
        setSelectAddressData({
            phone: currentAddressData.tel,
            address: currentAddressData.address,
            receiver: currentAddressData.name,
        });

        //修改弹出层是否显示
        setVisible(false);
    };

    //根据sids查询购物袋数据
    let getShopbagData = () => {
        axios({
            method: "get",
            url: "/commitShopcart",
            params: {
                sids: JSON.stringify(location.state.sids),
            },
        })
            .then((res) => {
                if (res.data.code === 700) {
                    return navigate("/login");
                }

                if (res.data.code === 50000) {
                    res.data.result.forEach((item) => {
                        payInfo.count += item.count;
                        payInfo.total +=
                            item.count * item.price;
                    });

                    setPayProduct(res.data.result);
                    setPayInfo({ ...payInfo });
                }
            })
            .catch((err) => {});
    };

    //结算
    let pay = () => {
        axios({
            method: "post",
            url: "/pay",
            data: {
                ...selectAddressData,
                sids: JSON.stringify(location.state.sids),
            },
        })
            .then((res) => {
                if (res.data.code === 700) {
                    return navigate("/login");
                }

                if (res.data.code === 60000) {
                    dispatch(
                        changeCount(
                            shopbagCount - payInfo.count
                        )
                    );
                    // navigate('/order');
                    navigate("/menu");
                }
            })
            .catch((err) => {});
    };

    useEffect(() => {
        if (!location.state) {
            return navigate("/shopbag");
        }

        getAddressList();
        getShopbagData();
    }, []);

    return (
        <div className="pay">
            <NavBar
                title="订单结算"
                leftText="返回"
                rightText=""
                onClickLeft={() => navigate(-1)}
            />
            <div>
                <div className="biao-ding">
                    <div className="biao-bb">
                        <Cell
                            title="选择地址"
                            isLink
                            onClick={() => {
                                setVisible(true);
                            }}
                        />
                        <div className="address-info">
                            <div className="di-ren">
                                <div className="di-ziti">
                                    {
                                        selectAddressData.receiver
                                    }
                                </div>
                                <div className="hui-di">
                                    {
                                        selectAddressData.phone
                                    }
                                </div>
                            </div>
                            <div className="hui-di-ii">
                                {selectAddressData.address}
                            </div>
                        </div>
                    </div>
                </div>

                <div className="ding-xia">
                    <div className="pay-info">
                        <div className="d-xiang">
                            订单信息
                        </div>
                        {payProduct.map((item, index) => {
                            return (
                                <div
                                    className="p-item"
                                    key={index}
                                >
                                    <ProductCard
                                        num={item.count}
                                        price={item.price}
                                        desc={
                                            <div>
                                                <div className="tang">
                                                    {
                                                        item.rule
                                                    }
                                                </div>
                                            </div>
                                        }
                                        title={
                                            <div>
                                                <div className="p-name">
                                                    {
                                                        item.name
                                                    }
                                                </div>
                                                <div className="y-na">
                                                    {
                                                        item.enname
                                                    }
                                                </div>
                                            </div>
                                        }
                                        thumb={
                                            item.small_img
                                        }
                                    />
                                </div>
                            );
                        })}
                    </div>
                    <div>
                        <div className="shang-pin">
                            共计 {payInfo.count} 件商品
                        </div>
                        <div className="zon-ji">
                            总价：&yen;{payInfo.total}
                        </div>
                    </div>
                </div>
                <div className="di-hou">
                    <Button
                        round
                        block
                        type="primary"
                        onClick={() => {
                            pay();
                        }}
                    >
                        结算
                    </Button>
                </div>
            </div>

            <Popup
                visible={visible}
                onClose={() => setVisible(false)}
                position="bottom"
                closeable
            >
                <div style={{ padding: "30px 20px" }}>
                    <Radio.Group
                        value={selectIndex}
                        onChange={(index) => {
                            selectAddress(index);
                        }}
                    >
                        {addressData.map((item, index) => {
                            return (
                                <div key={index}>
                                    <Cell
                                        center
                                        title={
                                            <div className="p-text">
                                                <div className="p-user">
                                                    {
                                                        item.name
                                                    }
                                                </div>
                                                <div>
                                                    {
                                                        item.tel
                                                    }
                                                </div>
                                            </div>
                                        }
                                        label={
                                            <div>
                                                {
                                                    item.address
                                                }
                                            </div>
                                        }
                                        icon={
                                            <Radio
                                                checked={
                                                    item.isCheck
                                                }
                                                checkedColor="#ee0a24"
                                                name={index}
                                            ></Radio>
                                        }
                                    />
                                </div>
                            );
                        })}
                    </Radio.Group>
                </div>
                <div
                    className="tui"
                    onClick={() => {
                        navigate("/Address");
                    }}
                >
                    <div className="demo-button">
                        <Button type="primary" block round>
                            新增地址
                        </Button>
                    </div>
                </div>
            </Popup>
        </div>
    );
}

export default Pay;
